//
//  PPostVideoHandler.m
//  PPostAudioFunction
//
//  Created by carlos on 14-5-2.
//  Copyright (c) 2014年 carlosk. All rights reserved.
//

#import "PPostVideoHandler.h"
#import "AudioToolbox/AudioToolbox.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import "PPostVideoUtil.h"
#import "ChatRecorderView.h"
#import "UIView+Animation.h"

#define kCancelOriginY          ([[UIScreen mainScreen]bounds].size.height-70)
#define kRecorderViewRect       CGRectMake(80, 120, 160, 160)
@interface PPostVideoHandler()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>{
    CGFloat                 curCount;           //当前计数,初始为0
    ChatRecorderView        *recorderView;      //录音界面
    CGPoint                 curTouchPoint;      //触摸点
    BOOL                    canNotSend;         //不能发送
    NSTimer                 *timer;
}

@property (retain, nonatomic)   AVAudioRecorder     *recorder;
@property (assign, nonatomic)           NSInteger               maxRecordTime;//最大录音时间
@property (copy, nonatomic)             NSString                *recordFileName;//录音文件名
@property (copy, nonatomic)             NSString                *recordFilePath;//录音文件路径
@property(nonatomic,strong)AVAudioPlayer *play;
@end

@implementation PPostVideoHandler

static PPostVideoHandler *handler;
//单例
+(PPostVideoHandler *)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handler = [[PPostVideoHandler alloc] init];
    });
    return handler;
}

- (void)dealloc{
    recorderView= nil;
    self.recorder = nil;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.maxRecordTime = kDefaultMaxRecordTime;
    }
    return self;
}
#define COTest NO
#pragma mark - 开始录音
- (void)startRecord:(UIView *)topView{
    //添加触摸事件
    if (!COTest) {
        
        NSString *_fileName = [PPostVideoUtil getCurrentTimeString];
        //设置文件名和录音路径
        self.recordFileName = _fileName;
        self.recordFilePath = [PPostVideoUtil getPathByFileName:self.recordFileName ofType:@"wav"];
        
        //初始化录音
        self.recorder = [[AVAudioRecorder alloc]initWithURL:[NSURL URLWithString:self.recordFilePath]
                                                   settings:[PPostVideoUtil getAudioRecorderSettingDict]
                                                      error:nil];
        self.recorder.delegate = self;
        self.recorder.meteringEnabled = YES;
        
        [self.recorder prepareToRecord];
        //还原计数
        curCount = 0;
        //还原发送
        canNotSend = NO;
        
        //开始录音
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        [self.recorder record];
    }else{
    }
    

    
    //启动计时器
    [self startTimer];
    
    //显示录音界面
    [self initRecordView];
    [UIView showView:recorderView
         animateType:AnimateTypeOfPopping
           finalRect:kRecorderViewRect
          completion:^(BOOL finish){
              if (finish){
                  //注册nScreenTouch事件
                  [self addScreenTouchObserver];
              }
          } withTopView:topView];

    //设置遮罩背景不可触摸
    [UIView setTopMaskViewCanTouch:NO];
}
#pragma mark - 初始化录音界面
- (void)initRecordView{
    if (recorderView == nil)
        recorderView = [[ChatRecorderView alloc] init];
    //还原界面显示
    [recorderView restoreDisplay];
}
#pragma mark - 启动定时器
- (void)startTimer{
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateMeters) userInfo:nil repeats:YES];
}

#pragma mark - 停止定时器
- (void)stopTimer{
    if (timer && timer.isValid){
        [timer invalidate];
        timer = nil;
    }
}
#pragma mark - 更新音频峰值
- (void)updateMeters{
    if (self.recorder.isRecording){
        
        //更新峰值
        [self.recorder updateMeters];
        [recorderView updateMetersByAvgPower:[self.recorder averagePowerForChannel:0]];
        //        NSLog(@"峰值:%f",[recorder averagePowerForChannel:0]);
        
        //倒计时
        if (curCount >= self.maxRecordTime - 10 && curCount < self.maxRecordTime) {
            //剩下10秒
            recorderView.countDownLabel.text = [NSString stringWithFormat:@"录音剩下:%d秒",(int)(self.maxRecordTime-curCount)];
        }else if (curCount >= self.maxRecordTime){
            //时间到
            [self touchEnded:curTouchPoint];
        }
        curCount += 0.1f;
    }
}

#pragma mark - 移除触摸观察者
- (void)removeScreenTouchObserver{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"nScreenTouch" object:nil];//移除nScreenTouch事件
}
#pragma mark - 添加触摸观察者
- (void)addScreenTouchObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onScreenTouch:) name:@"nScreenTouch" object:nil];
}
-(void)onScreenTouch:(NSNotification *)notification {
    NSLog(@"onScreenTouch :%@",notification.userInfo);
    UIEvent *event=[notification.userInfo objectForKey:@"data"];
    NSSet *allTouches = event.allTouches;
    
    //如果未触摸或只有单点触摸
    if ((curTouchPoint.x == CGPointZero.x && curTouchPoint.y == CGPointZero.y) || allTouches.count == 1)
        [self transferTouch:[allTouches anyObject]];
    else{
        //遍历touch,找到最先触摸的那个touch
        for (UITouch *touch in allTouches){
            CGPoint prePoint = [touch previousLocationInView:nil];
            
            if (prePoint.x == curTouchPoint.x && prePoint.y == curTouchPoint.y)
                [self transferTouch:touch];
        }
    }
}
//传递触点
- (void)transferTouch:(UITouch*)_touch{
    CGPoint point = [_touch locationInView:nil];
    switch (_touch.phase) {
        case UITouchPhaseBegan:
            [self touchBegan:point];
            break;
        case UITouchPhaseMoved:
            [self touchMoved:point];
            break;
        case UITouchPhaseCancelled:
        case UITouchPhaseEnded:
            [self touchEnded:point];
            break;
        default:
            break;
    }
}
#pragma mark - 触摸开始
- (void)touchBegan:(CGPoint)_point{
    curTouchPoint = _point;
}
#pragma mark - 触摸移动
- (void)touchMoved:(CGPoint)_point{
    curTouchPoint = _point;
    //判断是否移动到取消区域
    canNotSend = _point.y < kCancelOriginY ? YES : NO;
    
    //设置取消动画
    [recorderView prepareToDelete:canNotSend];
}
#pragma mark - 触摸结束
- (void)touchEnded:(CGPoint)_point{
    //停止计时器
    [self stopTimer];
    
    curTouchPoint = CGPointZero;
    [self removeScreenTouchObserver];
    //停止录音
    if (self.recorder.isRecording)
        [self.recorder stop];
    
    if (canNotSend) {
        //取消发送，删除文件
        [PPostVideoUtil deleteFileAtPath:self.recordFilePath];
        if (self.doEndRecord) {
            self.doEndRecord(nil,nil,-1);
        }
    }else{
        //回调录音文件路径
        if (self.doEndRecord) {
            self.doEndRecord(self.recordFilePath,self.recordFileName,curCount);
        }
    }

}
//结束录音
- (void)endRecord{
    //停止计时器
    [self stopTimer];
    //如果时间在1秒之内,则不能发送
    canNotSend = curCount < 1;
    curTouchPoint = CGPointZero;
    [self removeScreenTouchObserver];
    [UIView hideViewByCompletion:^(BOOL finish){
        
        //停止录音
        if (self.recorder.isRecording)
            [self.recorder stop];
        
        if (canNotSend) {
            //取消发送，删除文件
            NSLog(@"不能发送,删除文件");
            [PPostVideoUtil deleteFileAtPath:self.recordFilePath];
            if (self.doEndRecord) {
                self.doEndRecord(nil,nil,-1);
            }
        }else{
            //回调录音文件路径
            if (self.doEndRecord) {
                self.doEndRecord(self.recordFilePath,self.recordFileName,curCount);
            }
        }
    }];
}

#pragma mark - AVAudioRecorder Delegate Methods
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"录音停止");
    
    [self stopTimer];
//    curCount = 0;
}
- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{
    NSLog(@"录音开始");
    [self stopTimer];
    curCount = 0;
}
- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags{
    NSLog(@"录音中断");
    [self stopTimer];
//    curCount = 0;
}
//播放
+(void)play:(NSString *)filePath{
    [self stopPlay];
    PPostVideoHandler *hander = [PPostVideoHandler sharedInstance];
    [hander play:filePath];
}

- (void)play:(NSString *)filePath{
    NSError *error;
    self.play = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
    self.play.delegate = self;
    //    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil];
    //    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:YES error:nil];
    [self.play prepareToPlay];
    [self.play play];

}
//是否是正在播放
+(BOOL)isPlay{
    PPostVideoHandler *hander = [PPostVideoHandler sharedInstance];
    return hander.play.isPlaying;
}
//停止播放
+(void)stopPlay{
    PPostVideoHandler *hander = [PPostVideoHandler sharedInstance];
    [hander.play stop];
}

#pragma mark AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    //播放结束了
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifiAudioPlayFinishedName object:nil];
}

@end
